package org.shock.ss.sms.commons.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.apache.struts2.ServletActionContext;

/**
 * 文件上传公用类
 * 
 * @author 朱启元
 * @since 2010-09-25
 */
public class UploadUtil {
	private static final int BUFFER_SIZE = 16 * 1024;

	/**
	 * 保存文件
	 * 
	 * @param file
	 *            上传的文件
	 * @param targetFile
	 *            指定存放的文件
	 */
	public static void saveFile(File file, File targetFile) {
		try {
			InputStream in = null;
			OutputStream out = null;
			if (file.length() > 0) {
				try {
					in = new BufferedInputStream(new FileInputStream(file),
							BUFFER_SIZE);
					out = new BufferedOutputStream(new FileOutputStream(
							targetFile), BUFFER_SIZE);
					byte[] buffer = new byte[BUFFER_SIZE];
					while (in.read(buffer) > 0) {
						out.write(buffer);
					}
				} finally {
					if (null != in) {
						in.close();
					}
					if (null != out) {
						out.close();
					}
				}
			} else {
				OutputStreamWriter os = null;
				os = new OutputStreamWriter(new FileOutputStream(targetFile));
				os.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取文件名的扩展名
	 * 
	 * @param fileName
	 *            文件名
	 * @return String
	 */
	public static String getExtention(String fileName) {
		String suffix = "";// 文件的扩展名
		if (fileName == null) {
			return suffix;
		}
		if (fileName.contains(".")) {
			int pos = fileName.lastIndexOf(".");
			suffix = fileName.substring(pos).toLowerCase();
		}
		return suffix;
	}

	/**
	 * 获取文件名的扩展名
	 * 
	 * @param fileName
	 *            文件名
	 * @return String 不带 "."
	 */
	public static String getExt(String fileName) {
		return getExtention(fileName).replace(".", "");
	}

	/**
	 * 传一路径和一文件名删除一文件 例如： delfile("/upload/movies","1232342242.rar")
	 * 
	 * @author qz
	 * @since 2010-09-20
	 */
	public static void deleteFile(String filePath) {
		File delFile = new File(filePath);
		delFile.delete();
	}
}
